<?php
class Link {
	public static function Build($link ,$type='http'){
		$base=(($type == 'http' || USE_SSL == 'no') ?'http://':'https://').getenv('SERVER_NAME');
		
		
		
		// if Http port is defined and different than default 
		if(defined('HTTP_SERVER_PORT') && HTTP_SERVER_PORT != '80' && strpos($base,'https') === false){
			//Append Server Port
			$base .=':'.HTTP_SERVER_PORT ;
			
		}
		$link =$base.VIRTUAL_LOCATION. $link ;
		
		//Escape Html 
		return htmlspecialchars($link,ENT_QUOTES);
	}
	
	public static function ToDepartment($departmentId,$page=1){
		
		$link =self::CleanUrlText(Catalog::GetDepartmentName($departmentId)) .
		'-d' .$departmentId . '/';
		
		//$link ='index.php?DepartmentId='.$departmentId;
		
		if($page > 1)
		$link .= 'page-' .$page . '/' ;
		//$link .= '&Page=' .$page;
		
		return self::Build($link);
	}
	
    public static function ToCategory($departmentId,$categoryId,$page =1){
    	
    	$link =self::CleanUrlText(Catalog::GetDepartmentName($departmentId)) .
		'-d' .$departmentId . '/' . 
    	 self::CleanUrlText(Catalog::GetcategoryName($categoryId)) .
		'-c' .$categoryId . '/' ;
		//$link ='index.php?DepartmentId='.$departmentId.
		//       '&CategoryId='.$categoryId;
		
		if($page >1)
		$link .= 'page-' .$page . '/' ;
		
		return self::Build($link);
	}
	
	public static function ToProduct($productId){
		
		$link = self::CleanUrlText(Catalog::GetProductName($productId)) .
		       '-p' .$productId . '/';
		
		return self::Build($link);
		
	}
	
	
	public static function ToIndex($page=1){
		
		$link ='';
		
		if($page >1){
			$link .= 'page-' .$page . '/' ;
			
		}
		return Link::Build($link);
	}
	
	public static function QueryStringToArray($queryString){
		
		$result =array();
		
		if($queryString != ""){
			
			$elements =explode('&',$queryString);
			
			foreach ($elements as $key=>$value) {
				
				$element =explode('=',$value);
				$result[urldecode($element[0])]= isset($element[1])?urldecode($element[1]) : '';
				
				
			}
			
		}
		return $result;
	}
	
	
	public static function CleanUrlText($string){
		
		//Remove all characters that are not a-z, 0-9, dash , underscore  or space 
		$not_acceptable_characters_regex ='#[^-a-zA-Z0-9_ ]#';
        $string =preg_replace($not_acceptable_characters_regex, '', $string);
        
        //Remove all leading trailing spaces 
        $string =trim($string);
        
        //change all dashes ,underscore and spaces to dashes 
        $string =preg_replace('#[-_ ]+#','-', $string);
        
        //Return the modified string 
        return strtolower($string) ;
		
	}
	
	public static function CheckRequest(){
		
		$proper_url ='';
		
		if(isset($_GET['Search']) || isset($_GET['SearchResults']) || isset($_GET['AddProduct'])){
			return;
			
		}elseif(isset($_GET['DepartmentId']) && isset($_GET['CategoryId'])){
			 if(isset($_GET['Page'])){
			 $proper_url = self::ToCategory($_GET['DepartmentId'], $_GET['CategoryId'] ,$_GET['Page']);
			 }else{
			 $proper_url = self::ToCategory($_GET['DepartmentId'], $_GET['CategoryId']);
			 }
		}elseif(isset($_GET['DepartmentId'])){
			 if(isset($_GET['Page'])){
			 $proper_url = self::ToDepartment($_GET['DepartmentId'],$_GET['Page']);
			 }else{
			 $proper_url = self::ToDepartment($_GET['DepartmentId']);
			 }
		}elseif(isset($_GET['ProductId'])){
		     if(isset($_GET['Page'])){
			 $proper_url = self::ToProduct($_GET['ProductId'],$_GET['Page']);
			 }else{
			 $proper_url = self::ToProduct($_GET['ProductId']);
			 }
		}else{
		     if(isset($_GET['Page'])){
			 $proper_url = self::ToIndex($_GET['Page']);
			 }else{
			 $proper_url = self::ToIndex();
			 }
		} 
		
		//Remove the virtual location from the  requested URL  so we can compare path 
		$requested_url= self::Build(str_replace(VIRTUAL_LOCATION,'', $_SERVER['REQUEST_URI']));
		
		//404 redirect if requested product ,category  or department doesnt exists 
		if(strstr($proper_url ,'/-'))
		{
			//Clean outout buffer 
			ob_clean();
			
			// load the 404 page 
			include '404.php';
			
			// clear the output buffer and stop execution 
			flush();
			ob_flush();
			ob_end_clean();
			exit();
			
		}
		
		// 301 redirect to proper url  if necessary 
		if($requested_url != $proper_url)
		{
		
		//clean output buffer 
		ob_clean();
		
		//Redirect 301 
		header('HTTP/1.1  301 Moved permanently');
		header('Location:' .$proper_url);
		
		//Clear the output buffer and stop execution 
		flush();
		ob_flush();
		ob_end_clean();
		exit();
		}
	 }
	 
	 
	 public static  function ToSearch(){
	 	
	 	return self::Build('index.php?Search');
	 	
	 } 
	 
	 public static function ToSearchResults($searchString,$allWords,$page=1){
	 	
	 	$link ='search-results/find';
	 	
	 	if(empty($searchString))
	 	$link .='/';
	 	else 
	 	$link.='-' .self::CleanUrlText($searchString) .'/';
	 	
	 	$link .='all-words-'.$allWords .'/';
	 	
	 	if($page >1)
	 	$link .='page-' .$page .'/';

	 	return self::Build($link);
	 	
	 }
	
	 public static function ToAddProduct($productId)
	 {
	 	return self::Build('index.php?AddProduct='.$productId);
	 }
	 
	public static function ToAdmin($params='')
	{
		$link ='admin.php';
		
		if($params != '')
		$link.='?'.$params;
		
		return self::Build($link ,'https');
	}
	
	public static function ToLogout()
	{
		return self::ToAdmin('Page=Logout');
	}
	
	public static function ToDepartmentsAdmin()
	{
		return self::ToAdmin('Page=Departments');
	}
	
	public static function ToDepartmentCategoriesAdmin($departmentId)
	{
		$link = 'Page=Categories&DepartmentId='.$departmentId ;
		
		return self::ToAdmin($link);
	}
	 
}